var express = require('express');
var Msdb = require("../../../db/Msdb.js");
var router = express.Router();   //可使用 express.Router 类创建模块化、可挂载的路由句柄
const jwt = require('jsonwebtoken');
var Excel = require('exceljs');
var multer = require('multer');
var UUID = require('uuid');
var request = require("request");
const { getxl_util, getnowdate, saveczlog_util, res_util, checkbysql, addformfield, getnowdate_djh, setformfield,
   insert_table, update_table_wstr, update_table_byid, resutdata_to_formdata, resutdata_to_formdata_arr, save_qlczslog_util,
   usequery } = require('./server_util.js')

const log = require('../../../logger.js');
const db = require('../../../db/Redisdb.js');
const { sendHttp } = require('./ship_note.js');
var logger = require('../../../logger.js').logger;

//定时发布的项目发布更新
async function xm_fb() {
   let db = new Msdb()
   let rtdata = await usequery(`select * from shipSRM_xm where xmzt='待发布' and shzt='审核通过' and fbsj is not null`)
   for (var i = 0; i < rtdata.length; i++) {
      var item = rtdata[i];
      let fbsjdate = new Date(item.fbsj.toISOString().slice(0, 19).replace('T', ' ')).getTime()
      //如果发布时间小于当前时间，则更新为待应标   
      if (fbsjdate < new Date().getTime()) {
         let sql = `update shipSRM_xm set xmzt='待应标' where id='${item.id}'`
         await db.update(sql)
         await saveczlog_util(sql, { ygxm: '管理员', ygbh: 'admin' }, '', '更新项目状态待应标', '更新', 'shipSRM_xm')
         let gysList = await usequery(`select * from shipSRM_xm_gysmx where mainid='${item.id}'`)
         let dhList = []
         for (var j = 0; j < gysList.length; j++) {
            dhList.push(gysList[j].lxdh)
         }
         let msg = `您好，项目名称：${item.xmmc}已经开始应标了，请您登录系统查看详情，系统地址为http://111.77.154.58:2233`
         // let msgresult = await sendHttp(dhList.join(','), msg)
         // for (var i = 0; i < dhList.length; i++) {
         //    let xlid = await getxl_util()
         //    await usequery(`insert into shipSRM_fsjl(id,create_time,create_by,phone,dxnr,fszt,tjsj,uid) 
         //    values('${xlid}',getdate(),'${item.create_by}','${dhList[i]}','${msg}','发送中',getdate(),'${JSON.parse(msgresult).uid}')`)
         // }

      }
   }
}
//项目应标截止更新项目状态
async function xm_ybjz() {
   let db = new Msdb()
   let rtdata = await usequery(`select a.*,b.ybgyssl from shipSRM_xm a left join (select mainid,count(*) as ybgyssl from shipSRM_xm_gysmx where ybzt='已应标' 
      group by mainid) b on a.id=b.mainid where a.xmzt='待应标' and a.ybjzsj is not null`)
   for (var i = 0; i < rtdata.length; i++) {
      var item = rtdata[i];

      let ybjzdate = new Date(item.ybjzsj.toISOString().slice(0, 19).replace('T', ' ')).getTime()
      //如果应标截止时间小于当前时间，则更新为待竞价  
      if (ybjzdate < new Date().getTime()) {
         //如果应标供应商数量为0，则更新为已流标
         if (item.ybgyssl == 0 || item.ybgyssl == null) {
            let sql = `update shipSRM_xm set xmzt='已流标' where id='${item.id}'`
            await db.update(sql)
            await saveczlog_util(sql, { ygxm: '管理员', ygbh: 'admin' }, '', '更新项目状态已流标', '更新', 'shipSRM_xm')
         } else {
            let sql = `update shipSRM_xm set xmzt='待竞价' where id='${item.id}'`
            await db.update(sql)
            await saveczlog_util(sql, { ygxm: '管理员', ygbh: 'admin' }, '', '更新项目状态待竞价', '更新', 'shipSRM_xm')
         }
      }
   }
}

//定时开标的项目发布更新
async function xm_kb() {
   let db = new Msdb()
   let rtdata = await usequery(`select * from shipSRM_xm where xmzt='待竞价' and kbsj is not null`)
   for (var i = 0; i < rtdata.length; i++) {
      var item = rtdata[i];
      let kbsjdate = new Date(item.kbsj.toISOString().slice(0, 19).replace('T', ' ')).getTime()
      //如果开标时间小于当前时间，则更新为竞价结束  
      if (kbsjdate < new Date().getTime()) {
         let dqljzsj = new Date(new Date().getTime() + item.mlcx * 60 * 1000).toLocaleString()
         let sql = `update shipSRM_xm set xmzt='竞价中',dqlc=1,dqlkssj=getdate(),dqljzsj='${dqljzsj}',jjzt='竞价中' where id='${item.id}'`
         await db.update(sql)
         await saveczlog_util(sql, { ygxm: '管理员', ygbh: 'admin' }, '', '更新项目状态竞价中', '更新', 'shipSRM_xm')
         let gysList = await usequery(`select * from shipSRM_xm_gysmx where mainid='${item.id}'`)
         let dhList = []
         for (var j = 0; j < gysList.length; j++) {
            dhList.push(gysList[j].lxdh)
         }
         let msg = `您好，项目名称：${item.xmmc}已经开始竞价了，请您登录系统查看详情，系统地址为http://111.77.154.58:2233`
         // let msgresult = await sendHttp(dhList.join(','), msg)
         // for (var i = 0; i < dhList.length; i++) {
         //    let xlid = await getxl_util()
         //    await usequery(`insert into shipSRM_fsjl(id,create_time,create_by,phone,dxnr,fszt,tjsj,uid) 
         //    values('${xlid}',getdate(),'${item.create_by}','${dhList[i]}','${msg}','发送中',getdate(),'${JSON.parse(msgresult).uid}')`)
         // }
      }
   }
}

//项目投标截止更新项目状态
async function xm_tbjz() {
   let db = new Msdb()
   let rtdata = await usequery(`select * from shipSRM_xm where xmzt='竞价中' and tbjzsj is not null`)
   for (var i = 0; i < rtdata.length; i++) {
      var item = rtdata[i];
      let tbjzdate = new Date(item.tbjzsj.toISOString().slice(0, 19).replace('T', ' ')).getTime()
      //如果投标截止时间小于当前时间，则更新为待竞价  
      if (tbjzdate < new Date().getTime()) {
         let sql = `update shipSRM_xm set xmzt='竞价结束' where id='${item.id}'`
         await db.update(sql)
         await saveczlog_util(sql, { ygxm: '管理员', ygbh: 'admin' }, '', '更新项目状态竞价结束', '更新', 'shipSRM_xm')
      }
   }
}
//更新竞价数据
async function update_gysjb() {
   let db = new Msdb()
   let rtdata = await usequery(`select * from shipSRM_xm where xmzt='竞价中'`)
   for (var i = 0; i < rtdata.length; i++) {
      var item = rtdata[i];
      let dqlkssj = new Date(item.dqlkssj.toISOString().slice(0, 19).replace('T', ' ')).getTime()
      let dqljzsj = new Date(item.dqljzsj.toISOString().slice(0, 19).replace('T', ' ')).getTime()
      if (item.dqlc < item.jjls && item.xmzt == '竞价中') {
         if (item.jjzt == '竞价休息') {
            //如果竞价开始时间小于当前时间，则更新竞价状态为竞价中  
            if (dqljzsj + item.mljg * 60 * 1000 < new Date().getTime()) {
               // 计算下一轮开始时间
               let xylkssj = new Date(dqljzsj + item.mljg * 60 * 1000).toLocaleString()
               // 计算下一轮结束时间
               let xyljzsj = new Date(new Date(xylkssj).getTime() + item.mlcx * 60 * 1000).toLocaleString()
               let sql = `update shipSRM_xm set jjzt='竞价中',dqlc=dqlc+1,dqlkssj='${xylkssj}',dqljzsj='${xyljzsj}' where id='${item.id}'`
               await db.update(sql)
               await saveczlog_util(sql, { ygxm: '管理员', ygbh: 'admin' }, '', '更新竞价状态竞价中', '更新', 'shipSRM_xm')
            }
            
            let rtdata = await usequery(`select 
               DENSE_RANK() OVER (PARTITION BY bjwlmxid ORDER BY blbj ${item.jjgz == '价高优先' ? 'desc' : 'asc'}) AS rank, *
               from shipSRM_gys_bjmx where xmid='${item.id}' and bjlc='${item.dqlc}'`)
            for (let i = 0; i < rtdata.length; i++) {
               await db.update(`update shipSRM_gys_bjmx set blpm='${rtdata[i].rank}' where id='${rtdata[i].id}'`)
            }
         }
         else if (item.jjzt == '待竞价') {
            //如果竞价结束时间小于当前时间，则更新竞价状态为竞价结束  
            if (dqlkssj < new Date().getTime()) {
               let sql = `update shipSRM_xm set jjzt='竞价中' where id='${item.id}'`
               await db.update(sql)
               await saveczlog_util(sql, { ygxm: '管理员', ygbh: 'admin' }, '', '更新竞价状态竞价中', '更新', 'shipSRM_xm')

            }



         }
         else if (item.jjzt == '竞价中') {
            //如果竞价结束时间小于当前时间，则更新竞价状态为竞价结束  
            if (dqljzsj < new Date().getTime()) {
               let sql = `update shipSRM_xm set jjzt='竞价休息' where id='${item.id}'`
               await db.update(sql)
               await saveczlog_util(sql, { ygxm: '管理员', ygbh: 'admin' }, '', '更新竞价状态竞价休息', '更新', 'shipSRM_xm')
            }

         }
      }
      else if (item.dqlc == item.jjls && item.xmzt == '竞价中') {
         //如果竞价结束时间小于当前时间，则更新竞价状态为竞价结束  
         if (dqljzsj < new Date().getTime()) {
            let sql = `update shipSRM_xm set jjzt='竞价结束',xmzt='竞价结束' where id='${item.id}'`
            await db.update(sql)
            await saveczlog_util(sql, { ygxm: '管理员', ygbh: 'admin' }, '', '更新竞价状态竞价结束', '更新', 'shipSRM_xm')
         }
      }
   }
}


async function update_gysjb_pm() {
   let db = new Msdb()
   let rtdata = await usequery(`select * from shipSRM_xm where xmzt='竞价结束'`)
   for (var i = 0; i < rtdata.length; i++) {
      var item = rtdata[i];
      let rtdata2 = await usequery(`select 
            ROW_NUMBER() OVER (PARTITION BY bjwlmxid ORDER BY blbj ${item.jjgz == '价高优先' ? 'desc' : 'asc'}) AS rank, *
            from shipSRM_gys_bjmx where xmid='${item.id}' and bjlc='${item.dqlc}'`)
      for (let i = 0; i < rtdata2.length; i++) {
         await db.update(`update shipSRM_gys_bjmx set blpm='${rtdata2[i].rank}' where id='${rtdata2[i].id}'`)
      }
   }
}



module.exports = {
   xm_fb,
   xm_ybjz,
   xm_tbjz,
   xm_kb,
   update_gysjb,
   update_gysjb_pm
}; 